<template>
  <div class="system-bg">
    <el-card class="user-card" shadow="hover">
      <div slot="header" class="card-header-horizontal">
        <div class="header-title">成员管理</div>
        <div class="header-btn-group">
          <el-upload :action="importUrl" :show-file-list="false" :headers="getUploadHeaders()" @success="onImportSuccess" @error="onImportError" style="margin-right:8px;">
            <el-button class="outline-btn" icon="el-icon-upload">导入</el-button>
          </el-upload>
          <el-button class="outline-btn" icon="el-icon-download" @click="exportMembers" style="margin-right:8px;">导出</el-button>
          <el-button class="add-btn" type="primary" icon="el-icon-plus" @click="onShowAdd">新增成员</el-button>
        </div>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-bar">
        <el-form-item label="姓名"><el-input v-model="searchForm.name" placeholder="输入姓名" size="small" /></el-form-item>
        <el-form-item label="家族">
          <el-select v-model="searchForm.clanId" placeholder="全部" size="small" @change="onSearchClanChange">
            <el-option label="全部" value="" />
            <el-option v-for="clan in clanList" :key="clan.id" :label="clan.name" :value="clan.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分支">
          <el-select v-model="searchForm.branchId" placeholder="全部" size="small" :disabled="!searchForm.clanId">
            <el-option label="全部" value="" />
            <el-option v-for="branch in searchFilteredBranchList" :key="branch.id" :label="branch.name" :value="branch.id" />
          </el-select>
        </el-form-item>
        <el-form-item><el-button type="primary" size="small" @click="load(1)">搜索</el-button></el-form-item>
        <el-form-item><el-button size="small" @click="resetSearch">重置</el-button></el-form-item>
      </el-form>
      <el-table :data="list" style="width:100%" class="member-table" highlight-current-row>
        <el-table-column prop="photo" label="照片" width="80">
          <template slot-scope="scope">
            <img v-if="scope.row.photo" :src="getImageUrl(scope.row.photo)" style="width:50px;height:50px;border-radius:4px;object-fit:cover;cursor:pointer;" @click="previewImage(scope.row.photo)" />
            <span v-else style="color:#999;font-size:12px;">无照片</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="gender" label="性别" width="60">
          <template slot-scope="scope">{{ scope.row.gender === 'M' ? '男' : (scope.row.gender === 'F' ? '女' : '-') }}</template>
        </el-table-column>
        <el-table-column prop="generation" label="世代" width="60" />
        <el-table-column prop="clanName" label="家族" width="120" />
        <el-table-column prop="branchName" label="分支" width="120" />
        <el-table-column prop="birthDate" label="出生日期" width="120" />
        <!-- <el-table-column prop="death_date" label="去世日期" width="100" />
        <el-table-column prop="fatherName" label="父亲" width="100" />
        <el-table-column prop="motherName" label="母亲" width="100" />
        <el-table-column prop="spouseName" label="配偶" width="100" /> -->
        <el-table-column prop="contact" label="联系方式" width="120" />
        <el-table-column label="籍贯" width="200">
          <template slot-scope="scope">
            {{ scope.row.nativeProvinceName }} {{ scope.row.nativeCityName }} {{ scope.row.nativeCountyName }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="currentAddress" label="现住地址" width="150" /> -->
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope"><el-tag :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '在世' : '已故' }}</el-tag></template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <div class="action-btn-group">
              <el-button size="mini" class="edit-btn" @click="edit(scope.row)">编辑</el-button>
              <el-button size="mini" class="delete-btn" @click="remove(scope.row)">删除</el-button>
              <el-button size="mini" class="detail-btn" @click="viewDetail(scope.row)">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        :page-size="size"
        :current-page="current"
        @current-change="load"
        @size-change="handleSizeChange"
        layout="total, prev, pager, next, jumper, ->, sizes"
        :page-sizes="[10, 20, 50, 100]"
        class="member-pagination"
      />
    </el-card>
    <el-dialog :visible.sync="showAdd" title="新增成员" class="fade-dialog custom-dialog" :close-on-click-modal="false" width="820px">
      <el-form :model="form" label-width="90px" class="dialog-form">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="照片" class="nowrap-label">
              <div class="photo-upload-container">
                <el-upload
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handlePhotoSuccess"
                  :before-upload="beforePhotoUpload"
                  :on-error="handlePhotoError"
                  :headers="uploadHeaders"
                  accept="image/*"
                  class="photo-upload">
                  <img v-if="form.photo" :src="getImageUrl(form.photo)" class="photo-preview" />
                  <i v-else class="el-icon-plus photo-uploader-icon"></i>
                </el-upload>
                <div v-if="form.photo" class="photo-actions">
                  <el-button size="mini" type="danger" @click="removePhoto">删除照片</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="姓名" class="nowrap-label"><el-input v-model="form.name" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" class="nowrap-label"><el-select v-model="form.gender" placeholder="请选择"><el-option label="男" value="M"/><el-option label="女" value="F"/></el-select></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="世代" class="nowrap-label">
                  <el-select v-model="form.generation" placeholder="请选择世代" clearable>
                    <el-option v-for="gen in generationList" :key="gen" :label="`第${gen}代`" :value="gen" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="家族" class="nowrap-label"><el-select v-model="form.clanId" placeholder="请选择" @change="onClanChange"><el-option v-for="clan in clanList" :key="clan.id" :label="clan.name" :value="clan.id" /></el-select></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="分支" class="nowrap-label"><el-select v-model="form.branchId" placeholder="请选择" :disabled="!form.clanId"><el-option v-for="branch in filteredBranchList" :key="branch.id" :label="branch.name" :value="branch.id" /></el-select></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" class="nowrap-label"><el-date-picker v-model="form.birthDate" type="date" placeholder="选择日期" style="width:100%" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="去世日期" class="nowrap-label"><el-date-picker v-model="form.deathDate" type="date" placeholder="选择日期" style="width:100%" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="父亲" class="nowrap-label">
                  <el-select v-model="form.fatherId" filterable placeholder="请选择父亲" clearable @change="onFatherChange">
                    <el-option v-for="member in allMembers" :key="member.id" :label="member.name" :value="member.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="母亲" class="nowrap-label">
                  <el-select v-model="form.motherId" filterable placeholder="请选择母亲" clearable @change="onMotherChange">
                    <el-option v-for="spouse in fatherSpouses" :key="spouse.spouseId" :label="spouse.spouseName" :value="spouse.spouseId" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="子女排序" class="nowrap-label child-order-item">
                  <div class="child-order-container">
                    <el-input-number 
                      v-model="form.childOrder" 
                      :min="1" 
                      :max="20" 
                      placeholder="自动分配"
                      controls-position="right"
                      size="small"
                      style="width: 120px;"
                    />
                    <span class="form-tip">（可选，系统会自动分配）</span>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系方式" class="nowrap-label"><el-input v-model="form.contact" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="籍贯" class="nowrap-label">
                  <el-cascader
                    v-model="regionCascaderValue"
                    :options="regionOptions"
                    :props="regionProps"
                    clearable
                    placeholder="请选择籍贯（省/市/区县/镇）"
                    @change="onRegionCascaderChange"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="现住地址" class="nowrap-label"><el-input v-model="form.currentAddress" type="textarea" :rows="2" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="个人事迹" class="nowrap-label"><el-input v-model="form.story" type="textarea" :rows="2" /></el-form-item>
              </el-col>
              <!-- <el-col :span="24">
                <el-form-item label="OCR内容" class="nowrap-label"><el-input v-model="form.ocr_content" type="textarea" :rows="2" /></el-form-item>
              </el-col> -->
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAdd=false">取消</el-button>
        <el-button type="primary" @click="add">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showEdit" title="编辑成员" class="fade-dialog custom-dialog" :close-on-click-modal="false" width="820px">
      <el-form :model="form" label-width="90px" class="dialog-form">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="照片" class="nowrap-label">
              <div class="photo-upload-container">
                <el-upload
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handlePhotoSuccess"
                  :before-upload="beforePhotoUpload"
                  :on-error="handlePhotoError"
                  :headers="uploadHeaders"
                  accept="image/*"
                  class="photo-upload">
                  <img v-if="form.photo" :src="getImageUrl(form.photo)" class="photo-preview" />
                  <i v-else class="el-icon-plus photo-uploader-icon"></i>
                </el-upload>
                <div v-if="form.photo" class="photo-actions">
                  <el-button size="mini" type="danger" @click="removePhoto">删除照片</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="姓名" class="nowrap-label"><el-input v-model="form.name" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" class="nowrap-label"><el-select v-model="form.gender" placeholder="请选择"><el-option label="男" value="M"/><el-option label="女" value="F"/></el-select></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="世代" class="nowrap-label">
                  <el-select v-model="form.generation" placeholder="请选择世代" clearable>
                    <el-option v-for="gen in generationList" :key="gen" :label="`第${gen}代`" :value="gen" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="家族" class="nowrap-label"><el-select v-model="form.clanId" placeholder="请选择" @change="onClanChange"><el-option v-for="clan in clanList" :key="clan.id" :label="clan.name" :value="clan.id" /></el-select></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="分支" class="nowrap-label"><el-select v-model="form.branchId" placeholder="请选择" :disabled="!form.clanId"><el-option v-for="branch in filteredBranchList" :key="branch.id" :label="branch.name" :value="branch.id" /></el-select></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" class="nowrap-label"><el-date-picker v-model="form.birthDate" type="date" placeholder="选择日期" style="width:100%" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="去世日期" class="nowrap-label"><el-date-picker v-model="form.deathDate" type="date" placeholder="选择日期" style="width:100%" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="父亲" class="nowrap-label">
                  <el-select v-model="form.fatherId" filterable placeholder="请选择父亲" clearable @change="onFatherChange">
                    <el-option v-for="member in allMembers" :key="member.id" :label="member.name" :value="member.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="母亲" class="nowrap-label">
                  <el-select v-model="form.motherId" filterable placeholder="请选择母亲" clearable>
                    <el-option v-for="spouse in fatherSpouses" :key="spouse.spouseId" :label="spouse.spouseName" :value="spouse.spouseId" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="子女排序" class="nowrap-label child-order-item">
                  <div class="child-order-container">
                    <el-input-number 
                      v-model="form.childOrder" 
                      :min="1" 
                      :max="20" 
                      placeholder="自动分配"
                      controls-position="right"
                      size="small"
                      style="width: 120px;"
                    />
                    <span class="form-tip">（可选，系统会自动分配）</span>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系方式" class="nowrap-label"><el-input v-model="form.contact" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="籍贯" class="nowrap-label">
                  <el-cascader
                    v-model="regionCascaderValue"
                    :options="regionOptions"
                    :props="regionProps"
                    clearable
                    placeholder="请选择籍贯（省/市/区县/镇）"
                    @change="onRegionCascaderChange"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="现住地址" class="nowrap-label"><el-input v-model="form.currentAddress" type="textarea" :rows="2" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="个人事迹" class="nowrap-label"><el-input v-model="form.story" type="textarea" :rows="2" /></el-form-item>
              </el-col>
              <!-- <el-col :span="24">
                <el-form-item label="OCR内容" class="nowrap-label"><el-input v-model="form.ocr_content" type="textarea" :rows="2" /></el-form-item>
              </el-col> -->
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEdit=false">取消</el-button>
        <el-button type="primary" @click="update">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getMemberList, addMember, updateMember, deleteMember, getMemberSpouses } from '@/api/member';
import { getClanList } from '@/api/clan';
import { getBranchList, getBranchesByClanId } from '@/api/branch';
import { getProvinces, getCities, getCounties, getTowns } from '@/api/region';
export default {
  data() {
    return {
      list: [],
      total: 0,
      size: 10,
      current: 1,
      showAdd: false,
      showEdit: false,
      form: { id: null, name: '', gender: '', generation: '', clanId: null, branchId: null, birthDate: '', deathDate: '', fatherId: null, motherId: null, photo: '', ocr_content: '', contact: '', nativeProvinceCode: '', nativeCityCode: '', nativeCountyCode: '', nativeTownCode: '', currentAddress: '', sort_order: 0, status: 1, story: '', childOrder: null },
      searchForm: { name: '', gender: '', clanId: '', branchId: '' },
      clanList: [],
      branchList: [],
      filteredBranchList: [],
      searchFilteredBranchList: [], // 新增：家族查询下的分支
      regionOptions: [], // 四级联动数据
      regionCascaderValue: [], // 级联选择器选中值
      regionProps: {
        lazy: true,
        lazyLoad: this.loadRegionNode,
        value: 'code',
        label: 'name',
        children: 'children',
        emitPath: true,
        checkStrictly: false
      },
      importUrl: '/api/v1/members/import',
      uploadUrl: '/api/v1/upload/member-photo',
      uploadHeaders: { 'Authorization': 'Bearer ' + (localStorage.getItem('token') || '') },
      allMembers: [], // Added allMembers to store all members for search
      fatherSpouses: [], // 父亲的配偶列表
      generationList: Array.from({length: 50}, (_, i) => i + 1) // 生成1-50代的选项
    };
  },
  created() {
    this.load(); this.loadClans(); this.loadBranches(); this.loadAllMembers();
    // 初始化省级数据（懒加载模式下只需初始化options为空数组即可）
    this.searchFilteredBranchList = [];
  },
  methods: {
    async load(page = 1) {
      this.current = page;
      const params = { page, size: this.size, ...this.searchForm };
      const data = await getMemberList(params);
      this.list = data.records || data.list || [];
      this.total = data.total;
      this.size = data.size || this.size;
      this.current = data.current || page;
    },
    handleSizeChange(newSize) {
      this.size = newSize;
      this.load(1);
    },
    async loadClans() {
      const data = await getClanList({ page: 1, size: 1000 });
      this.clanList = data.records || [];
    },
    async loadBranches() {
      const data = await getBranchList({ page: 1, size: 1000 });
      this.branchList = data.records || [];
    },
    // 家族选择变化时，加载对应的分支列表
    async onClanChange(clanId) {
      console.log('家族选择变化，家族ID:', clanId, '当前模式:', this.showEdit ? '编辑' : '新增');
      // 只有在新增模式下才清空分支选择
      if (!this.showEdit) {
        this.form.branchId = null; // Changed from '' to null
      }
      this.filteredBranchList = [];

      if (clanId) {
        try {
          // 根据家族ID获取对应的分支列表
          const data = await getBranchesByClanId(clanId);
          this.filteredBranchList = data || [];
          console.log('获取到的分支列表:', this.filteredBranchList);
        } catch (error) {
          console.error('获取分支列表失败:', error);
          this.filteredBranchList = [];
        }
      }
    },
    async onSearchClanChange(clanId) {
      this.searchForm.branchId = '';
      if (!clanId) {
        this.searchFilteredBranchList = [];
        return;
      }
      try {
        const data = await getBranchesByClanId(clanId);
        this.searchFilteredBranchList = data || [];
      } catch (e) {
        this.searchFilteredBranchList = [];
      }
    },
    async loadAllMembers() { // New method to load all members
      const data = await getMemberList({ page: 1, size: 1000 });
      this.allMembers = data.records || [];
    },
    
    // 父亲变化时加载配偶列表
    async onFatherChange() {
      console.log('父亲变化，fatherId:', this.form.fatherId);
      if (this.form.fatherId) {
        try {
          const response = await getMemberSpouses(this.form.fatherId);
          console.log('配偶API响应:', response);
          if (response && response.code === 0) {
            this.fatherSpouses = response.data || [];
          } else if (response && Array.isArray(response)) {
            this.fatherSpouses = response;
          } else {
            this.fatherSpouses = [];
          }
          console.log('加载的配偶列表:', this.fatherSpouses);
          // 清空母亲选择
          this.form.motherId = null;
        } catch (error) {
          console.error('加载父亲配偶失败:', error);
          this.fatherSpouses = [];
        }
      } else {
        this.fatherSpouses = [];
        this.form.motherId = null;
      }
    },
    // 母亲选择变化时记录选择的值
    onMotherChange() {
      console.log('母亲选择变化，motherId:', this.form.motherId);
      console.log('当前配偶列表:', this.fatherSpouses);
      const selectedSpouse = this.fatherSpouses.find(spouse => spouse.spouseId === this.form.motherId);
      console.log('选中的配偶:', selectedSpouse);
    },
    // 懒加载地区节点（修正api调用方式，避免api is not a function错误）
    async loadRegionNode(node, resolve) {
      let level = node.level || 0;
      let parentCode = node.data ? node.data.code : null;
      let api;
      if (level === 0) {
        api = getProvinces;
      } else if (level === 1) {
        api = getCities;
      } else if (level === 2) {
        api = getCounties;
      } else if (level === 3) {
        api = getTowns;
      } else {
        resolve([]);
        return;
      }
      let data;
      if (level === 0) {
        data = await api();
      } else {
        data = await api(parentCode);
      }
      const nextLevel = level + 1;
      resolve((data || []).map(item => ({
        ...item,
        leaf: nextLevel === 4 // 只有镇/街道为叶子节点
      })));
    },
    // 选择籍贯后自动填充form的四个code字段
    onRegionCascaderChange(val) {
      this.form.nativeProvinceCode = val[0] || '';
      this.form.nativeCityCode = val[1] || '';
      this.form.nativeCountyCode = val[2] || '';
      this.form.nativeTownCode = val[3] || '';
    },
    // 编辑时自动回显
    async edit(row) {
      console.log('编辑成员数据:', row);
      this.form = { ...row };
      this.showEdit = true;
      // 级联回显
      this.regionCascaderValue = [row.nativeProvinceCode, row.nativeCityCode, row.nativeCountyCode, row.nativeTownCode].filter(Boolean);

      // 如果编辑的成员有家族ID，加载对应的分支列表
      if (this.form.clanId) {
        console.log('加载家族分支，家族ID:', this.form.clanId, '分支ID:', this.form.branchId);
        await this.onClanChange(this.form.clanId);
        console.log('加载的分支列表:', this.filteredBranchList);
        // 确保分支ID的类型匹配
        if (this.form.branchId) {
          // 将分支ID转换为数字类型进行比较
          const branchIdNum = Number(this.form.branchId);
          const branchExists = this.filteredBranchList.some(branch => 
            Number(branch.id) === branchIdNum
          );
          console.log('分支ID匹配结果:', branchExists, '分支ID:', branchIdNum);
          if (!branchExists) {
            console.warn('分支ID不在当前家族的分支列表中:', this.form.branchId);
            // 如果分支不存在，可以选择清空或保持原值
            // this.form.branchId = '';
          }
        }
      }
      
      // 如果有父亲，加载父亲的配偶列表
      if (this.form.fatherId) {
        await this.onFatherChange();
      }
    },
    // 新增时清空级联
    onShowAdd() {
      this.form = { id: null, name: '', gender: '', generation: '', clanId: null, branchId: null, birthDate: '', deathDate: '', fatherId: null, motherId: null, photo: '', ocrContent: '', contact: '', nativeProvinceCode: '', nativeCityCode: '', nativeCountyCode: '', nativeTownCode: '', currentAddress: '', sortOrder: 0, status: 1, story: '', childOrder: null };
      this.regionCascaderValue = [];
      this.showAdd = true;
    },
    async add() {
      try {
        await addMember(this.form);
        this.$message.success('成员新增成功');
        this.showAdd = false;
        this.load();
      } catch (e) {
        this.$message.error('成员新增失败');
      }
    },
    async update() {
      try {
        await updateMember(this.form);
        this.$message.success('成员信息已保存');
        this.showEdit = false;
        this.load();
      } catch (e) {
        this.$message.error('成员信息保存失败');
      }
    },
    async remove(row) {
      this.$confirm('确定要删除该成员吗？此操作不可恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteMember(row.id);
          this.$message.success('成员已删除');
          this.load();
        } catch (e) {
          this.$message.error('成员删除失败');
        }
      }).catch(() => {
        // 用户取消，无需处理
      });
    },
    exportMembers() {
      window.open('/api/v1/members/export');
      this.$message.success('成员导出已开始');
    },
    viewDetail(row) {
      this.$router.push(`/member/detail/${row.id}`);
    },
    // 照片上传相关方法
    getImageUrl(photoPath) {
      if (!photoPath) return '';
      if (photoPath.startsWith('http')) {
        return photoPath;
      }
      return photoPath; // Use relative path since proxy handles it
    },
    previewImage(photoPath) {
      if (photoPath) {
        const imageUrl = this.getImageUrl(photoPath);
        this.$alert(`<img src="${imageUrl}" style="max-width:100%;max-height:400px;" />`, '照片预览', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '关闭'
        });
      }
    },
    handlePhotoSuccess(response) {
      if (response.code === 0) {
        this.form.photo = response.data;
        this.$message.success('照片上传成功');
      } else {
        this.$message.error(response.msg || '照片上传失败');
      }
    },
    beforePhotoUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    handlePhotoError() {
      this.$message.error('照片上传失败');
    },
    removePhoto() {
      this.$confirm('确定要删除这张照片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.photo = '';
        this.$message.success('照片已删除');
      }).catch(() => {});
    },
    onImportSuccess() {
      this.$message.success('成员导入成功');
      this.load();
    },
    onImportError() {
      this.$message.error('成员导入失败');
    },
    getUploadHeaders() {
      return {
        'Authorization': 'Bearer ' + (localStorage.getItem('token') || '')
      };
    },
    resetSearch() {
      this.searchForm = { name: '', gender: '', clanId: '', branchId: '' };
      this.searchFilteredBranchList = [];
      this.load(1);
    }
  }
};
</script>
<style scoped>
.system-bg {
  min-height: 80vh;
  background: linear-gradient(135deg, #f4f6fa 60%, #e0e7ff 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 0;
  animation: fadeIn 0.8s;
}
.user-card {
  width: 1100px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.10);
  background: rgba(255,255,255,0.95);
  transition: box-shadow 0.3s;
}
.card-header-horizontal {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
}
.header-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
}
.header-btn-group {
  display: flex;
  align-items: center;
  background: none;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
}
.header-btn-group .el-button {
  margin-right: 8px;
  height: 34px;
  font-size: 15px;
  padding: 0 18px;
  display: flex;
  align-items: center;
}
.header-btn-group .el-button:last-child {
  margin-right: 0;
}
.add-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
}
.add-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}
.outline-btn {
  background: #fff;
  border: 1px solid #6a82fb;
  color: #6a82fb;
  margin-right: 8px;
  transition: all 0.2s;
}
.outline-btn:hover {
  background: #6a82fb;
  color: #fff;
}
.member-table {
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 18px;
}
.member-table ::v-deep .el-table__row:hover {
  background: #f0f7ff !important;
  transition: background 0.2s;
}
.edit-btn {
  background: #fff;
  border: 1px solid #6a82fb;
  color: #6a82fb;
  /* margin-right: 5px; */
  transition: all 0.2s;
  /* min-width: 62px; */
}
.edit-btn:hover {
  background: #6a82fb;
  color: #fff;
}
.delete-btn {
  background: #fff;
  border: 1px solid #fc5c7d;
  color: #fc5c7d;
  transition: all 0.2s;
}
.delete-btn:hover {
  background: #fc5c7d;
  color: #fff;
}
.detail-btn {
  background: #fff;
  border: 1px solid #909399;
  color: #606266;
  border-radius: 6px;
  transition: all 0.2s;
}
.detail-btn:hover {
  background: #f4f6fa;
  color: #409EFF;
  border-color: #409EFF;
}
.action-btn-group {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 12px;
}
.action-btn-group .el-button {
  min-width: 55px;
  /* font-size: 14px; */
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
  box-sizing: border-box;
}
.action-btn-group .el-button:last-child {
  margin-right: 0;
}

.member-pagination {
  margin-top: 18px;
  text-align: right;
}
.member-pagination ::v-deep .el-pager li {
  border-radius: 6px;
  transition: background 0.2s;
}
.member-pagination ::v-deep .el-pager li.active {
  background: #6a82fb;
  color: #fff;
}
.fade-dialog ::v-deep .el-dialog__wrapper {
  animation: fadeIn 0.4s;
}
.custom-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  background: #fafdff;
  padding-bottom: 0;
}
.dialog-form {
  padding: 12px 0 0 0;
}
.dialog-form ::v-deep .el-form-item {
  margin-bottom: 22px;
}
.dialog-footer {
  text-align: right;
  padding: 8px 0 8px 0;
}
.dialog-footer .el-button {
  min-width: 80px;
  border-radius: 6px;
  font-weight: 500;
  margin-left: 8px;
}
.dialog-footer .el-button--primary {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
}
.dialog-footer .el-button--primary:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}
.nowrap-label ::v-deep .el-form-item__label {
  white-space: nowrap;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
  white-space: nowrap;
  line-height: 1.4;
}

.photo-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.photo-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.photo-upload:hover {
  border-color: #409EFF;
}

.photo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.photo-preview {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.photo-actions {
  margin-top: 8px;
}

/* 子女排序容器样式 */
.child-order-container {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.child-order-container .el-input-number {
  flex-shrink: 0;
  min-width: 120px;
}

.child-order-container .form-tip {
  flex: 1;
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
  line-height: 32px;
  white-space: nowrap;
}

/* 子女排序表单项特殊样式 */
.child-order-item ::v-deep .el-form-item__content {
  display: flex;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .child-order-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .child-order-container .form-tip {
    margin-left: 0;
    line-height: 1.4;
  }
  
  .child-order-item ::v-deep .el-form-item__content {
    flex-direction: column;
    align-items: flex-start;
  }
}

/* 统一表单输入框样式 */
.dialog-form ::v-deep .el-input,
.dialog-form ::v-deep .el-select,
.dialog-form ::v-deep .el-date-picker {
  width: 100%;
}

.dialog-form ::v-deep .el-input-number {
  width: 120px;
}

/* 确保子女排序字段在所有情况下都正确显示 */
.child-order-item {
  margin-bottom: 22px;
}

.child-order-item ::v-deep .el-form-item__label {
  color: #606266; /* Element UI 默认表单标签色 */
  padding-right: 12px;
  font-weight: 500;
}

.child-order-item ::v-deep .el-form-item__content {
  display: flex;
  align-items: center;
  min-height: 32px;
}

/* 优化数字输入框样式 */
.child-order-container .el-input-number ::v-deep .el-input__inner {
  text-align: center;
}

.child-order-container .el-input-number ::v-deep .el-input-number__decrease,
.child-order-container .el-input-number ::v-deep .el-input-number__increase {
  border: none;
  background: #f5f7fa;
  color: #606266;
}

.child-order-container .el-input-number ::v-deep .el-input-number__decrease:hover,
.child-order-container .el-input-number ::v-deep .el-input-number__increase:hover {
  background: #e4e7ed;
  color: #409eff;
}
</style>
